##
# This class represents an image which handles the storage of the image in the
# File System
class Image < ActiveRecord::Base
	belongs_to :user
  # call save_picture after the save-method was invoced
  after_save :save_picture
  include ImageHelper
  
  ##
  # This method assings the filename and content type and checks them for
  # errors. Thus the method may rise an NoImage or FileExists exception.
  # @params incomming_file is an instance of a CGI-File object.
  def picture=(incomming_file)
    @temp_file = incomming_file
    self.file = santize_filename(incomming_file.original_filename)
    @file = self.file
    @content_type = incomming_file.content_type
    if(!(@content_type =~ /^image/))
      raise ImageHelper::NoImage
    end
    tmp = Image.find(:all, :conditions => { :file => @file })
    logger.info tmp.inspect
    if (tmp.length > 0)
      raise ImageHelper::FileExists
    end
  end
  
  private
  
  ##
  # This method stores the image in the file system. It is invoked after the 
  # save-method was successfully called.
  def save_picture 
    if(@temp_file)
      File.open("#{RAILS_ROOT}/media/#{@file}", "wb") do |f|
        f.write(@temp_file.read)
      end
    end
  end
  
  ##
  # this method replaces the C:\.... from the Internet Explorer and returns
  # only the "real" name of the file without the path.
  # @params val is the string which will be checked
  # @return the name of the file without the path is returned.
  def santize_filename(val)
    # get only the filename, not the whole path
    just_filename = val.gsub(/^.*(\\|\/)/, '')
    # NOTE: Filename.basename doesn't work right with Windows paths on Unix
    # INCORRECT: just_filename = File.basename(val.gsub('\\\\', '/'))
    # Finally, replace all non alphanumeric, underscore or periods with underscore
    @filename = just_filename.gsub(/[^\w\.\-]/, '_')
  end
end
